#Search-Tissue

#library packages
library(ggplot2)
library(dplyr)
library(data.table)
library(stringr)

library(optparse)

option_list <- list(
  make_option("--i", default = "", type = "character", help = "input file"),
  make_option("--m", default = "", type = "character", help = "meta file"),
  make_option("--c", default = "", type = "character", help = "color file"),
  make_option("--g", default = "", type = "character", help = "group"),
  make_option("--p", default = "", type = "character", help = "phenotype names use for sample filter"),
  make_option("--d", default = "", type = "character", help = "dataset names use for sample filter"),
  make_option("--l", default = "", type = "character", help = "log"),
  make_option("--o", default = "", type = "character", help = "output png file")
)
opt <- parse_args(OptionParser(option_list = option_list))

#import source data
expr<-fread(opt$i) %>%
  as.data.frame()
rownames(expr)<-expr$circID
expr<-expr[,-1]
meta<-read.table(opt$m,header = T,stringsAsFactors = F,sep = '\t')
mypal<-read.table(opt$c)[,1] %>%
  as.character()

#change strings into factors #修改
meta$Phenotype<-factor(meta$Phenotype,levels = c('Fetal', 'Normal', 'NAFLD', 'ALD', 'Viral Hepatitis', 'Fibrosis','Cirrhosis','Dysplastic Nodule',
                                                 'HCC','ADJ_HCC', 'Mixed HCC-ICC'))
meta$Age = factor(meta$Age,levels = c('19w','20w','22w','24w','1-17','18-49','50-69','>=70'))
meta$Inflammation = factor(meta$Inflammation,levels = c('None','Mild','Medium','Severe'))
meta$Fibrosis = factor(meta$Fibrosis,levels = c('None','Low','High','Cirrhosis'))

#dim parameters and extract corresponding data #修改
group<-opt$g
phenotype<-  opt$p %>%
  str_split(";") %>%
  unlist()
dataset<-opt$d %>%
  str_split(";") %>%
  unlist() # or specific datasets
filter<-list(phenotype = phenotype, dataset = dataset)
logscale<-opt$l
gene<-rownames(expr)[1] # or other input
meta.filter<-meta[(meta$Phenotype %in% filter$phenotype) & (meta$Dataset %in% filter$dataset),]
expr.gene<-expr[gene, meta.filter$Run]
meta.filter<-mutate(meta.filter,expr = as.numeric(expr.gene),log2expr = log2(as.numeric(expr.gene)+1),
                    group = meta.filter[,which(colnames(meta.filter)==group)])
meta.filter = meta.filter[!is.na(meta.filter$group),] #修改

#calculate freq
freq<-as.data.frame(table(meta.filter$group))
freq<-freq[freq$Freq!=0,]
meta.filter$group<-factor(meta.filter$group,levels = freq$Var1,labels = paste(freq$Var1,'\n(',freq$Freq,')',sep = '')) #修改

#plot #修改
png(file=opt$o,width=2000,height=1200,res=300)
if (logscale == 'Yes') {
  ggplot(meta.filter)+geom_boxplot(aes(x=group,y=log2expr,color=group),outlier.size=0.8)+
    scale_color_manual(values = mypal)+
    theme_bw()+theme(legend.position = 'none')+labs(y='Log2(CPM+1)',x=group,title = gene)+
    theme(axis.title.x = element_blank(),plot.title=element_text (hjust=0.5),
          axis.text.x = element_text(size = 7,angle = 45,hjust = 1,vjust = 1)) #修改
} else {
  ggplot(meta.filter)+geom_boxplot(aes(x=group,y=expr,color=group),outlier.size=0.8)+
    scale_color_manual(values = mypal)+
    theme_bw()+theme(legend.position = 'none')+labs(y='CPM',x=group,title = gene)+
    theme(axis.title.x = element_blank(),plot.title=element_text (hjust=0.5),
          axis.text.x = element_text(size = 7,angle = 45,hjust = 1,vjust = 1)) #修改
}
dev.off()

#export csv #修改
meta.filter$Size<-str_replace(str_extract(as.character(meta.filter$group),'(\\d+)'),'(|)','')
meta.filter$Group<-str_replace(meta.filter$group,'\n\\(\\d+\\)','')
meta.filter1<-select(meta.filter,Run,Group,Size,Dataset,expr,log2expr)
write.csv(meta.filter1,file = paste('gene.csv',sep = ''),row.names = F)
